package com.htdz.filter;

import com.htdz.util.JsonUtil;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;

import javax.servlet.http.HttpServletRequest;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Map;

@Aspect
@Component
public class ControllerInterceptor {
    private final Logger logger = LoggerFactory.getLogger(this.getClass());

    @Pointcut("execution(* com.htdz.controller..*(..)) && @annotation(org.springframework.web.bind.annotation.RequestMapping)")
    public void controllerMethodPointcut(){}

    @Around("controllerMethodPointcut()")
    public Object Interceptor(ProceedingJoinPoint proceedingJoinPoint)
    {
        //变量定义
        MethodSignature methodSignature;
        Object result =null;
        Map<String,String> parameterMap;
        RequestAttributes requestAttributes;
        HttpServletRequest request;
        Enumeration<String> enumeration;
        String parameter;
        try
        {
            requestAttributes= RequestContextHolder.getRequestAttributes();

            request = (HttpServletRequest) requestAttributes.resolveReference(RequestAttributes.REFERENCE_REQUEST);

            methodSignature = (MethodSignature) proceedingJoinPoint.getSignature();

            logger.info("URL请求:"+request.getRequestURL());

            logger.info("开始调用方法:"+methodSignature.getDeclaringTypeName()+"."+methodSignature.getName());

            enumeration= request.getParameterNames();

            parameterMap = new HashMap<>();

            while (enumeration.hasMoreElements()){
                parameter = enumeration.nextElement();
                parameterMap.put(parameter,request.getParameter(parameter));
            }

            logger.info("请求参数:"+ JsonUtil.obj2json(parameterMap));

            result   = proceedingJoinPoint.proceed();

            logger.info("请求结果:"+result);

        }
        catch (Exception ex)
        {
            logger.info("拦截器异常: ", ex);
        }
        catch (Throwable ex) {
            logger.info("拦截器异常: ", ex);
        }

        return result;
    }
}
